/*
 * Copyright (c) 2013-2015 Charkey. All rights reserved.
 *
 * This software is the confidential and proprietary information of Charkey.
 * You shall not disclose such Confidential Information and shall use it only
 * in accordance with the terms of the agreements you entered into with Charkey.
 *
 * Charkey MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
 *
 * Charkey SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING,
 * MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 */

package cn.simastudio.talos.ucpaas.client;

import cn.simastudio.talos.ucpaas.model.SMSResponse;
import cn.simastudio.talos.ucpaas.model.TemplateSMS;
import cn.simastudio.talos.ucpaas.utils.codec.MD5Utils;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * Usage: UCPaaS 短信发送Client
 *
 * @author Charkey
 * @date 2015/7/2 20:45
 */
@Component
@SuppressWarnings("SpringJavaAutowiringInspection")
public class UCPaaSClient {

    private Cache configurationCache;

    @Autowired
    private CacheManager cacheManager;

    public SMSResponse sendSMS(String content, Integer validMinutes, String sendTo, String templateId) throws IOException {
        String MockUCPaaSSwitch = configurationCache.get("MockUCPaaSSwitch").get() + "";
        if ("1".equals(MockUCPaaSSwitch)) {
            return SMSResponse.getMockResponse();
        }
        String UCPaaSAppId = configurationCache.get("UCPaaSAppId").get() + "";
        String UCPaaSTemplateId = configurationCache.get(templateId).get() + "";
        String UCPaaSAccountSid = configurationCache.get("UCPaaSAccountSid").get() + "";
        String UCPaaSAuthToken = configurationCache.get("UCPaaSAuthToken").get() + "";
        String UCPaaSSMSApi = configurationCache.get("UCPaaSSMSApi").get() + "";
        String UCPaaSSMSDatetimeFormat = configurationCache.get("UCPaaSSMSDatetimeFormat").get() + "";

        String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern(UCPaaSSMSDatetimeFormat));
        String SigParameter = MD5Utils.md5Digest(UCPaaSAccountSid + UCPaaSAuthToken + date).toUpperCase();
        String Authorization = Base64.encodeBase64String((UCPaaSAccountSid + ":" + date).getBytes());

        String url = UCPaaSSMSApi.replace("{UCPaaSAccountSid}", UCPaaSAccountSid).replace("{SigParameter}", SigParameter);

        HttpPost httpPost = new HttpPost(url);

        httpPost.setHeader(HttpHeaders.ACCEPT, "application/json;charset=UTF-8");
        httpPost.setHeader(HttpHeaders.AUTHORIZATION, Authorization);
        httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8");

        TemplateSMS templateSMS = new TemplateSMS();
        templateSMS.setAppId(UCPaaSAppId);
        templateSMS.setTemplateId(UCPaaSTemplateId);
        templateSMS.setTo(sendTo);
        templateSMS.setParam(content + "," + validMinutes);

        String body = templateSMS.toSMSContent();

        BasicHttpEntity requestBody = new BasicHttpEntity();
        requestBody.setContent(new ByteArrayInputStream(body.getBytes("UTF-8")));
        requestBody.setContentLength(body.getBytes("UTF-8").length);

        httpPost.setEntity(requestBody);

        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity responseEntity = response.getEntity();
        String result = "";
        if (responseEntity != null) {
            result = EntityUtils.toString(responseEntity, "UTF-8");
        }
        // 确保HTTP响应内容全部被读出或者内容流被关闭
        EntityUtils.consume(responseEntity);

        return SMSResponse.getInstanceFromRespJson(result);
    }

    public SMSResponse sendSMS(String content, String sendTo, String templateId) throws IOException {
        String MockUCPaaSSwitch = configurationCache.get("MockUCPaaSSwitch").get() + "";
        if ("1".equals(MockUCPaaSSwitch)) {
            return SMSResponse.getMockResponse();
        }
        String UCPaaSAppId = configurationCache.get("UCPaaSAppId").get() + "";
        String UCPaaSTemplateId = configurationCache.get(templateId).get() + "";
        String UCPaaSAccountSid = configurationCache.get("UCPaaSAccountSid").get() + "";
        String UCPaaSAuthToken = configurationCache.get("UCPaaSAuthToken").get() + "";
        String UCPaaSSMSApi = configurationCache.get("UCPaaSSMSApi").get() + "";
        String UCPaaSSMSDatetimeFormat = configurationCache.get("UCPaaSSMSDatetimeFormat").get() + "";

        String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern(UCPaaSSMSDatetimeFormat));
        String SigParameter = MD5Utils.md5Digest(UCPaaSAccountSid + UCPaaSAuthToken + date).toUpperCase();
        String Authorization = Base64.encodeBase64String((UCPaaSAccountSid + ":" + date).getBytes());

        String url = UCPaaSSMSApi.replace("{UCPaaSAccountSid}", UCPaaSAccountSid).replace("{SigParameter}", SigParameter);

        HttpPost httpPost = new HttpPost(url);

        httpPost.setHeader(HttpHeaders.ACCEPT, "application/json;charset=UTF-8");
        httpPost.setHeader(HttpHeaders.AUTHORIZATION, Authorization);
        httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8");

        TemplateSMS templateSMS = new TemplateSMS();
        templateSMS.setAppId(UCPaaSAppId);
        templateSMS.setTemplateId(UCPaaSTemplateId);
        templateSMS.setTo(sendTo);
        templateSMS.setParam(content);

        String body = templateSMS.toSMSContent();

        BasicHttpEntity requestBody = new BasicHttpEntity();
        requestBody.setContent(new ByteArrayInputStream(body.getBytes("UTF-8")));
        requestBody.setContentLength(body.getBytes("UTF-8").length);

        httpPost.setEntity(requestBody);

        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity responseEntity = response.getEntity();
        String result = "";
        if (responseEntity != null) {
            result = EntityUtils.toString(responseEntity, "UTF-8");
        }
        // 确保HTTP响应内容全部被读出或者内容流被关闭
        EntityUtils.consume(responseEntity);

        return SMSResponse.getInstanceFromRespJson(result);
    }

    @PostConstruct
    public void afterPropertiesSet() {
        configurationCache = cacheManager.getCache("configurationCache");
    }

}
